var express = require('express');
var path = require('path');
var favicon = require('serve-favicon');
var logger = require('morgan');
var cookieParser = require('cookie-parser');
var bodyParser = require('body-parser');
var methodOverride = require('method-override');
var session = require('express-session');
var MongoStore = require('connect-mongo')(session);
var setting = require('./setting');
var flash = require('connect-flash');
var util = require('util');
var fs = require('fs');
var compression = require('compression');


var routes = require('./routes/index');
var users = require('./routes/users');

var accessLogfile = fs.createWriteStream('access.log', {flags: 'a'});
var errorLogfile = fs.createWriteStream('error.log', {flags: 'a'});

var app = express();

app.use(compression());
// view engine setup
app.set('views', path.join(__dirname, 'views'));
//app.engine("html",require("ejs").__express); // or   app.engine("html",require("ejs").renderFile);
app.set("view engine", "ejs");
//app.set('view engine', 'html');

// uncomment after placing your favicon in /public
//app.use(favicon(path.join(__dirname, 'public', 'favicon.ico')));
//app.use(logger('dev'));
app.use(logger("default", {stream: accessLogfile}))
app.use(bodyParser.json());
app.use(bodyParser.urlencoded({extended: false}));
app.use(cookieParser());
app.use(express.static(path.join(__dirname, 'public')));
app.use(flash());

app.use(session({
    secret: setting.coolieSecret,
    key: setting.db,
    cookie: {maxAge: 1000 * 60 * 60 * 24 * 30},
    resave: true,
    saveUninitialized: true,
    store: new MongoStore({
        /*db: setting.db*/
        url: 'mongodb://45.32.37.104/microblog'
    })
}));

app.use(function (req, res, next) {
    console.log("app.usr local");
    res.locals.user = req.session.user;
    res.locals.post = req.session.post;
    var error = req.flash('error');
    res.locals.error = error.length ? error : null;

    var success = req.flash('success');
    res.locals.success = success.length ? success : null;

    next();
});

app.use('/', routes);
app.use('/users', users);


//routes(app);
/*
 app.use('/', index);
 app.use('/hello', index);
 app.use('/users', users);
 app.use('/u/:user', index);
 app.use('/post', index);
 app.use('/reg' , index);
 app.use('/login', index);
 app.use('/logout', index);
 */


// catch 404 and forward to error handler
app.use(function (req, res, next) {
    var err = new Error('Not Found');
    err.status = 404;
    next(err);
});

if (app.get('env') === 'development') {
    app.use(function (err, req, res, next) {
        res.status(err.status || 500);
        res.render('error', {
            message: err.message,
            error: err
        });
    });
}
// error handler
app.use(function (err, req, res, next) {
    // set locals, only providing error in development
    //res.locals.message = err.message;
    //res.locals.error = req.app.get('env') === 'development' ? err : {};
    // render the error page
    res.status(err.status || 500);
    res.render('error', {
        message: err.message,
        error: {}
    });
});

if (app.get('env') === 'production') {
    app.use(function (err, req, res, next) {
        var meta = '[' + new Date() + '] ' + req.url + '\n';
        errorLogfile.write(meta + err.stack + '\n');
        next();
    })
}

module.exports = app;
